// utils/request.js

export default (url, method = 'GET', params = {}, needToken = true) => {
	const API_BASE_URL = process.env.VUE_APP_API_URL || 'http://localhost:8088'; // 使用环境变量或配置文件中的 API_BASE_URL
	const token = uni.getStorageSync('token');

	// 显示加载提示框
	uni.showLoading({
		title: "加载中",
		mask: true // 防止用户点击
	});

	return new Promise((resolve, reject) => {
		let headers = {};
		if (!needToken) {
		} else if (needToken && !token) {
			console.log('准备隐藏加载提示框');
			    uni.hideLoading(); // 立即隐藏加载提示框
			    uni.navigateTo({
			        url: '/pages/MyHomepage/Component/PasswordLogin',
			    });
			    setTimeout(() => {
			        reject('未登录，请先登录');
			    }, 100); // 等待100毫秒后再reject
		}


		uni.request({
			url: `${API_BASE_URL}${url}`,
			method: method,
			header: {
				token: token
			},
			data: params,
			success(res) {
				if (res.statusCode === 200) {
					resolve(res.data);
				} else {
					reject(`服务器返回错误：${res.statusCode}`);
				}
			},
			fail(err) {
				reject(`请求失败：${err}`);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
};